package com.cheyun.netsalev3.view

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.widget.Toast
import androidx.annotation.NonNull
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.cheyun.netsalev3.R
import com.cheyun.netsalev3.adapter.MyAdapter
import com.cheyun.netsalev3.bean.*
import com.cheyun.netsalev3.bean.basedata.BaseDataParam
import com.cheyun.netsalev3.bean.basedata.Expchar
import com.cheyun.netsalev3.bean.drive.DriveListInfo
import com.cheyun.netsalev3.databinding.ActivityAddDriveBinding
import com.cheyun.netsalev3.utils.*
import com.cheyun.netsalev3.viewmodel.AddDriveActivityViewModel
import com.cheyunkeji.er.utils.ToastUtil
import com.dou361.dialogui.DialogUIUtils
import com.dou361.dialogui.listener.DialogUIItemListener
import com.jeremyliao.liveeventbus.LiveEventBus
import java.io.File
import java.util.ArrayList

class AddDriveActivity : BaseActivity<ActivityAddDriveBinding>() {
    override fun initContentView(): Int {
        return R.layout.activity_add_drive
    }

    private var ed = EditDriveParam()
    private val PERMISSION_CAMERA_REQUEST_CODE = 0x00000012
    private val PERMISSION_WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 0x00000013
    private val PERMISSION_WRITE_EXTERNAL_STORAGE_REQUEST_CODE2 = 0x00000014
    private var photoUri: Uri? = null
    private var picPath: String? = null
    private val fileUri = File(Environment.getExternalStorageDirectory().path + "/photo.jpg")

    var tid = 0
    var activity:Activity? = null
    private var imageStr = ""
    private var data:DriveListInfo? = null
    var baseDataParam: BaseDataParam? = MySharedPreferences.getBaseData()

    override fun initViewModel(): ViewModel? {
        if(intent.hasExtra("data")){
            data =intent.getSerializableExtra("data") as DriveListInfo
        }

        ed.drivingnum = "1"
        if(data != null){
            ed.tid = data?.tid!!
            if(data?.uname!!.isNotEmpty()) {
                ed.uname = data?.uname!!
            }
            if(data?.phone!!.isNotEmpty()) {
                ed.phone = data?.phone!!
            }
            ed.reserveid = data?.id.toString()
            ed.reservetime = data?.reservetime!!

            if(data?.id !=0){
                ed.drivingnum = data?.drivingnum!!
                ed.driveuid = data?.owneruid!!
                ed.reserveseries = data?.reserveseries!!
                ed.reservespec = data?.reservespec!!
                ed.drivetype = data?.drivetype!!
                ed.isreserve = data?.isreserve!!
                ed.reserveday = data?.reserve_day!!
                ed.reservehalf = data?.reservehalfStr!!
                ed.licence = data?.licence!!

                ed.driveName = data?.ownername!!
                ed.reserveseriesname = data?.reserveseriesname!!
                ed.reservespecname = data?.reservespecname!!

            }
        }

        var factory = InjectorUtils.getAddDriveActivityViewModelFactory(ed)
        return ViewModelProviders.of(this, factory).get(AddDriveActivityViewModel::class.java)
    }

    override fun initData() {
        binding.viewModel?.driveNum?.observe(this, Observer {
            binding.etDrivenum.setText(it)
        })
        binding.viewModel?.startTime?.observe(this, Observer {
            binding.txtDtime.setText(it)
        })
        if(data!=null){
            if(data?.id!!>0){

                binding.txtXiaoyouche.text = data?.reserveseriesname+ " "+ data?.reservespecname
                binding.txtOwnername.text = data?.ownername!!
                binding.txtDtime.text = data?.reservehalfStr!!
                binding.txtDday.text = data?.reserve_day!!
                binding.etDrivenum.setText(data?.drivingnum)
                baseDataParam?.apply {
                    if(data?.drivetype !=null && data?.drivetype!!.isNotEmpty()){
                        if (this.drivetype != null) {
                            for (item in this.drivetype) {
                                if(item.id == data?.drivetype?.toInt())
                                    binding.txtDrivetypename.text = item.title
                            }
                        }
                    }
                    if(data?.isreserve!=null && data?.isreserve!!.isNotEmpty()){
                        if (this.reservetype != null) {
                            for (item in this.reservetype) {
                                if(item.id == data?.isreserve?.toInt())
                                    binding.txtIsreservename.text = item.title
                            }
                        }
                    }

                }
            }
        }

        binding.imgAdd.setOnClickListener {
            val strings = ArrayList<String>()
            strings.add("拍摄")
            strings.add("从手机相册选择")
            DialogUIUtils.showBottomSheetAndCancel(it.context, strings, "取消", object : DialogUIItemListener() {
                override fun onItemClick(text: CharSequence, position: Int) {
                    if (position == 0) {
                        if (
                                ContextCompat.checkSelfPermission(
                                        it.context,
                                        Manifest.permission.CAMERA) !== PackageManager.PERMISSION_GRANTED ||
                                ContextCompat.checkSelfPermission(
                                        it.context,
                                        Manifest.permission.READ_EXTERNAL_STORAGE) !== PackageManager.PERMISSION_GRANTED ||
                                ContextCompat.checkSelfPermission(
                                        it.context,
                                        Manifest.permission.WRITE_EXTERNAL_STORAGE) !== PackageManager.PERMISSION_GRANTED) {

                            //没有权限，申请权限。
                            ActivityCompat.requestPermissions(
                                    activity!!,
                                    arrayOf(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE),
                                    PERMISSION_CAMERA_REQUEST_CODE)
                        } else {
                            //有调起相机拍照。
                            gotoCarema()
                        }
                    } else {
                        val hasCameraPermission = ContextCompat.checkSelfPermission(it.context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        if (hasCameraPermission == PackageManager.PERMISSION_GRANTED) {
                            //调起相册。
                            gotoPhoto()
                        } else {
                            //没有权限，申请权限。
                            ActivityCompat.requestPermissions(activity!!,
                                    arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                                    PERMISSION_WRITE_EXTERNAL_STORAGE_REQUEST_CODE
                            )
                        }
                    }

                }
            }).show()
        }
    }


    override fun initView() {
        activity = this
        binding.viewModel?.setActivity(this)

        LiveEventBus.get()
                .with("uploadOrderImg", String::class.java)
                .observe(this, Observer {
                    if (!TextUtils.isEmpty(it)) {
                        imageStr = it
                        setImages()
                    }
                })

    }

    fun setImages(){
        Glide.with(this).load(Uri.parse(imageStr)).transform(GlideRoundTransform(this, 5)).into(binding.ivImg)
        binding.viewModel?.setImage(imageStr)
    }

    override fun onResume() {
        super.onResume()
        binding.addBut.isEnabled = true
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == 102) {
            data?.apply {
                var carBrandParam = getSerializableExtra("car") as CarBrandParam
                binding.viewModel?.setCarData(carBrandParam)
                binding.txtXiaoyouche.text = carBrandParam.seriesname+ " "+ carBrandParam.specname
                binding.txtDtime.text = ""
            }
        }else if(resultCode == 103){
            data?.apply {

                var reserveseries = getStringExtra("reserveseries")
                var reservespec = getStringExtra("reservespec")
                var reserveseriesname = getStringExtra("reserveseriesname")
                var reservespecname = getStringExtra("reservespecname")
                var reserveday = getStringExtra("reserveday")
                var licence = getStringExtra("licence")
                var reservehalf = getStringExtra("reservehalf")

                binding.viewModel?.setEditData(reserveday, reserveseries, reserveseriesname, reservespec, reservespecname, licence, reservehalf)
                binding.txtXiaoyouche.text = reserveseriesname+ " "+ reservespecname
                binding.txtDday.text = reserveday
                binding.txtDtime.text = reservehalf
            }
        }
        if (resultCode == Activity.RESULT_OK) {
            doPhoto(requestCode, data)
        }
    }

    private fun gotoCarema() {
        val captureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        if (ContextCompat.checkSelfPermission(activity!!,
                        Manifest.permission.CAMERA) !== PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(activity!!,
                        Manifest.permission.READ_EXTERNAL_STORAGE) !== PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(activity!!,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) !== PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this.activity!!, Manifest.permission.CAMERA)) {
                ToastUtil.toastLongMessage("您已经拒绝过一次")
            }
            ActivityCompat.requestPermissions(this.activity!!, arrayOf(Manifest.permission.CAMERA,
                    Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE), PERMISSION_WRITE_EXTERNAL_STORAGE_REQUEST_CODE2)
        } else {//有权限直接调用系统相机拍照
            if (hasSdcard()) {
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
                    photoUri = Uri.fromFile(fileUri)
                } else {
                    photoUri = FileProvider.getUriForFile(activity!!, this.activity!!.getPackageName() + ".provider", fileUri)
                }
//                PhotoUtils.takePicture(this.activity, photoUri, 1)
                if (photoUri != null) {
                    captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                    startActivityForResult(captureIntent, 1)
                }
            } else {
                ToastUtil.toastLongMessage("您没有存储卡")
            }
        }
    }

    fun gotoPhoto() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(Intent.createChooser(intent, "请选择图片"), 2)
    }

    fun hasSdcard(): Boolean {
        val state = Environment.getExternalStorageState()
        return state == Environment.MEDIA_MOUNTED
    }

    private fun doPhoto(requestCode: Int, data: Intent?) {
        if (requestCode == 1) {
            try {
                picPath = UriUtils.getTakePhotoPath(data);
                var impageUpload = ImageUploader();
                impageUpload.ossImg(activity!!,picPath);
            } catch (e: Exception) {
                e.printStackTrace()
            }

        } else if (requestCode == 2) {
            if (data == null) {
                ToastUtils.showLong("选择图片文件出错")
                return
            }
            photoUri = data.data
            if (photoUri == null) {
                ToastUtils.showLong("选择图片文件出错")
                return
            }
            if (ContextCompat.checkSelfPermission(this.activity!!,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE) !== PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this.activity!!,
                        arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 2
                )
            } else {
                picPath = UriUtils.getRealPathFromUriAboveApi19(activity, photoUri)
            }

            if(CommonFunc.isPic(picPath)){
                var impageUpload = ImageUploader();
                impageUpload.ossImg(activity!!,picPath);
            }else{
                Toast.makeText(activity, "选择图片文件不正确", Toast.LENGTH_LONG).show()
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, @NonNull permissions: Array<String>, @NonNull grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            PERMISSION_WRITE_EXTERNAL_STORAGE_REQUEST_CODE -> {
                //调用系统相机申请拍照权限回调
                if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (hasSdcard()) {
                        gotoPhoto()
                    } else {
                        ToastUtils.showLong("您没有存储卡")
                    }
                } else {
                    ToastUtils.showLong("请允许使用存储空间")
                }
            }
            2 -> {
                //调用系统相册申请Sdcard权限回调
                if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    gotoPhoto()
                } else {
                    ToastUtils.showLong("请允许使用存储空间")
                }
            }
            PERMISSION_CAMERA_REQUEST_CODE -> {
                if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //允许权限，有调起相机拍照。
                    gotoCarema()
                } else {
                    //拒绝权限，弹出提示框。
                    ToastUtils.showLong("请允许使用相机权限")
                }
            }
            PERMISSION_WRITE_EXTERNAL_STORAGE_REQUEST_CODE2 -> {
                if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //允许权限，有调起相机拍照。
                    gotoCarema()
                } else {
                    //拒绝权限，弹出提示框。
                    ToastUtils.showLong("请允许使用存储空间")
                }
            }
        }
    }
}
